define(['angular-sanitize'], function() {
    angular.module('app.keyword', ['ngSanitize'])
        .filter('keyword', keywordFilter);

    function keywordFilter($sce) {
        return function(items, keyword, name, limit) {
            var newItems = [];
            if (keyword) {
                var rkeyword = new RegExp(keyword, 'gi');
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    var text = item[name];
                    if (rkeyword.test(text)) {
                        var highlight = text.replace(rkeyword,
                            '<span style="color:whitesmoke;background-color:darkgrey;">$&</span>');
                        item['highlight'] = $sce.trustAsHtml(highlight);
                        newItems.push(item);
                        if (limit && newItems.length >= limit) {
                            return newItems;
                        }
                    }
                }
            } else {
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    item['highlight'] = $sce.trustAsHtml(item[name]);
                    newItems.push(item);
                    if (limit && newItems.length >= limit) {
                        return newItems;
                    }
                }
            }
            return newItems;
        }
    }
});
